import os
import json
import asyncio
from botpy import logging
from botpy.message import GroupMessage, Message
import matplotlib.pyplot as plt
import random


def copy_folder_on_hourly_basis(source_folder, destination_folder):
    while True:
        # 获取当前时间
        current_time = time.localtime()

        # 如果当前时间是整点
        if current_time.tm_min == 0 and current_time.tm_sec == 0:
            # 将源文件夹中的所有内容复制到目标文件夹中
            shutil.copytree(source_folder, destination_folder)

        # 等待1秒钟
        time.sleep(1)

async def send_message(message, time, msg_num, txt, picture_url = None):
    _log = logging.get_logger()
    await asyncio.sleep(time)
    if hasattr(message, 'group_openid'):
        if picture_url:
            media_0 = await message._api.post_group_file(
            group_openid=message.group_openid,
            file_type=1,
            url=picture_url,
            srv_send_msg=False
            )
            messageResult = await message._api.post_group_message(
            group_openid=message.group_openid,
            msg_type=7, 
            msg_id=message.id,
            msg_seq=msg_num,
            content=txt,
            media=media_0
            )
            _log.info(messageResult)
            return
        else:
            messageResult = await message._api.post_group_message(
                group_openid=message.group_openid,
                msg_type=0, 
                msg_id=message.id,
                msg_seq=msg_num,
                content=txt
                )
            _log.info(messageResult)
            return
    else:
        if picture_url:
            media_0 = await message._api.post_c2c_file(
            openid=message.author.user_openid,
            file_type=1,
            url=picture_url,
            srv_send_msg=False,
            )
            messageResult = await message._api.post_c2c_message(
            openid=message.author.user_openid, 
            msg_type=7, 
            msg_id=message.id, 
            msg_seq=msg_num,
            content=txt,
            media=media_0
            )
            _log.info(messageResult)
            return
        else:
            messageResult = await message._api.post_c2c_message(
            openid=message.author.user_openid, 
            msg_type=0, 
            msg_id=message.id, 
            msg_seq=msg_num,
            content=txt
            )


async def send_pic_message(message, time, msg_num, txt, pic_name):
    # 支持的图片格式
    supported_formats = ['.png', '.jpg', '.jpeg', '.bmp', '.gif']
    folder_name = '图片'
    # 尝试打开支持的图片格式
    for ext in supported_formats:
        file_name = '{}{}'.format(pic_name, ext)
        file_path = os.path.join(folder_name, file_name)
        try:
            with open(file_path, "rb") as f:
                image_data = f.read()
            break
        except FileNotFoundError:
            continue

    # 将图片数据编码为 base64 字符串
    base64_data = base64.b64encode(image_data).decode("utf-8")
    if hasattr(message, 'group_openid'):
        media_0 = await message._api.post_group_file(
        group_openid=message.group_openid,
        file_type=1,
        url=None,
        srv_send_msg=False,
        file_data=base64_data
        )
        messageResult = await message._api.post_group_message(
        group_openid=message.group_openid,
        msg_type=7, 
        msg_id=message.id,
        msg_seq=1,
        content=txt,
        media=media_0
        )
        _log.info(messageResult)
    else:
        media_0 = await message._api.post_c2c_file(
        openid=message.author.user_openid,
        file_type=1,
        url=None,
        srv_send_msg=False,
        file_data=base64_data
        )
        messageResult = await message._api.post_c2c_message(
        openid=message.author.user_openid, 
        msg_type=7, 
        msg_id=message.id, 
        msg_seq=1,
        content=txt,
        media=media_0
        )
        _log.info(messageResult)
        
        return


async def read_time(what):
    with open(f"data/配置.txt", 'r') as f:
        data = json.load(f)
    if what in data:
        return data[what]
    else:
        return "错误"



#查询txt文本中是否存在name值为value的项,返回name2值或者不存在
async def txt_exist(text: str, name1: str,value: str, name2 :str = None):
    with open(f"data/{text}.txt", 'r') as f:
        data = json.load(f)

    for item in data:
        if item.get(name1) == value:
            if name2 == None:
                return "存在"

            else: 
                return item.get(name2)
    return "不存在"

async def txt_write(text: str, name1: str,value1: str, name2 :str, value2):
    with open(f"data/{text}.txt", 'r') as f:
        data = json.load(f)
    for item in data:
        if item.get(name1) == value1:
            item[name2] = value2
            with open(f"data/{text}.txt", 'w') as f:
                json.dump(data, f, ensure_ascii=False, indent=4)
            return "存在"
    return "不存在"


async def player_read(number: str, name1 :str, name2 :str = None):
    uid = await txt_exist("player", "number", number, "id")
    if uid == "不存在":
        return "不存在该玩家！"
    with open(f"data/player/{uid}.txt", 'r') as f:
        data = json.load(f)
    if name2 == None:
        return data[name1]
    else:
        return data[name1][name2]

async def player_write(number: str, name1: str, name2 :str, value):
    id = await txt_exist("player", "number", number, "id")
    if id == "不存在":
        return "玩家信息不存在该玩家！"
    with open(f"data/player/{id}.txt", 'r') as f:
        data = json.load(f)
    if name2 == None:
        data[name1] = value
    else:
        data[name1][name2] = value
    with open(f"data/player/{id}.txt", 'w') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)

async def player_id(number):
    return await txt_exist("player", "number", number, "id")

async def player_name(uid):
    return await txt_exist("player", "id", uid, "nickname")

async def player_number(uid):
    return await txt_exist("player", "id", uid, "number")


async def bag_add(id, name, number):
    with open(f"data/bag/{id}.txt", 'r') as f:
        data = json.load(f)
        find = False
        for item in data["背包"]:
            if item["名称"] == name:
                find = True
                item["数量"] = int(item["数量"]) + int(number)
                break
        if not find:
            
            data["背包"].append({"名称": name, "数量": number})
    with open(f"data/bag/{id}.txt", 'w') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)

async def bag_reduce(id, name, number, if_empty = None):
    with open(f"data/bag/{id}.txt", 'r') as f:
        data = json.load(f)
        find = False
        for item in data["背包"]:
            if item["名称"] == name:
                find = True
                if if_empty == "强制":
                    data["背包"].remove(item)
                    break
                item["数量"] = int(item["数量"]) - int(number)
                #if item["数量"] < 0:
                #    return "不够"
                if item["数量"] == 0:
                    data["背包"].remove(item) 
                    break
        if not find:
            return "不够"
    with open(f"data/bag/{id}.txt", 'w') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)

async def bag_enough(id, name, number):
    with open(f"data/bag/{id}.txt", 'r') as f:
        data = json.load(f)
        find = False
        for item in data["背包"]:
            if item["名称"] == name:
                find = True
                item["数量"] = int(item["数量"]) - int(number)
                if item["数量"] < 0:
                    return "不够*缺{}".format(-item["数量"])
                if item["数量"] >= 0:
                    return "够了"
        if not find:
            return "不够*缺{}".format(number)

async def bag_number(id, name):
    with open(f"data/bag/{id}.txt", 'r') as f:
        data = json.load(f)
        find = False
        for item in data["背包"]:
            if item["名称"] == name:
                find = True
                return item["数量"]
        if not find:
            return 0

async def exp_up(level):
    with open(f"data/exp.txt", 'r') as f:
        data = json.load(f)
        txt = data[level]["经验"]
        return txt

async def sell_price(thing_name):
    with open(f"data/sell_price.txt", 'r') as f:
        data = json.load(f)
    if thing_name in data:
        return data[thing_name]
    else:
        return "不存在"

async def generate_code(length):
    """生成指定长度的数字验证码"""
    # 验证码由数字组成
    code = str(random.randint(0, 10**length-1)).zfill(length)
    return code